package cn.hpclub.server.controller.client;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.model.SysCodeType;
import cn.hpclub.server.model.SysCodeValue;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.service.MemberOrgService;
import cn.hpclub.server.service.SysCodeTypeService;

@API("/config")
public class ConfigController extends BaseClientController<SysCodeType>{

    private static Logger       logger       = LoggerFactory.getLogger(ConfigController.class);
    private static final String SERVICE_TYPE = "service_type";

    public void getProfileList(){
        JSONObject jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, ClientApiConstant.Msg.EXCEPTION,
                                       ClientApiConstant.Msg.EMPTY);
        try{
            String serviceType = getPara(SERVICE_TYPE, null);

            if(null == serviceType || "".equals(serviceType)){
                jo = setResponseObj(ClientApiConstant.ResultCode.PARAM_ERROR, ClientApiConstant.Msg.PARAEXCEPTION,
                                    ClientApiConstant.Msg.EMPTY);
                renderText(jo.toString());
                return;
            }

            List<Record> list = SysCodeType.dao.getCodeValueByTypeCode(serviceType);
            JSONArray jsonArray = toJsonArray(list);
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, ClientApiConstant.Msg.SUCCESS, jsonArray);

        }
        catch(Exception e){
            logger.error(e.getMessage());
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, e.getMessage(), ClientApiConstant.Msg.EMPTY);
        }

        renderText(jo.toString());
    }

    private JSONArray toJsonArray(List<Record> list){
        JSONArray jsonArray = new JSONArray();
        for(int i = 0; i < list.size(); i++){
            JSONObject json = new JSONObject();
            Record item = list.get(i);
            json.put("code", (null == item.getStr("code")) ? "" : item.getStr("code"));
            json.put("name", (null == item.getStr("name")) ? "" : item.getStr("name"));
            json.put("value", (null == item.getStr("value")) ? "" : item.getStr("value"));
            json.put("remark", (null == item.getStr("remark")) ? "" : item.getStr("remark"));
            json.put("sort", (null == item.getInt("sort")) ? 0 : item.getInt("sort"));

            jsonArray.put(json);
        }
        return jsonArray;
    }

    /**
     * 
     * @Title: getProfileListByUserInfo
     * @Description:根据人员所属地市渠道编码获取政企客户经理能够访问的数据（用于大掌柜-客户端-我的下面-德阳终端销售相关的H5页面入口）
     */
    public void getProfileListByUserInfo(){
        JSONObject jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, ClientApiConstant.Msg.FAIL,
                                       ClientApiConstant.Msg.EMPTY);
        try{
            String serviceType = getPara(SERVICE_TYPE, null);
            String userId = getPara("userId", null);
            String groupId = getPara("CityChannelId", null);// 当前用户所属地市分公司渠道编码，如德阳为17

            if(null == serviceType || "".equals(serviceType) || null == userId || "".equals(userId) || null == groupId
                    || "".equals(groupId)){
                jo = setResponseObj(ClientApiConstant.ResultCode.PARAM_ERROR, ClientApiConstant.Msg.PARAEXCEPTION,
                                    ClientApiConstant.Msg.EMPTY);
                renderText(jo.toString());
                return;
            }

            List<Record> list = null;
            if(isOnlyManagerVisibleOpen()){// 如果“只有政企客户经理可见开关”打开，需要判断用户是否政企客户经理
                boolean isAccountsManager = MemberOrgService.service.isAccountsManager(userId);
                if(isAccountsManager){// 如果是政企客户经理，根据地市渠道编码取数据
                    list = SysCodeTypeService.service.getProfileListByGroupId(serviceType, groupId);
                }
            } else{// 如果“只有政企客户经理可见开关”关闭，只直接根据地市渠道编码取数据
                list = SysCodeTypeService.service.getProfileListByGroupId(serviceType, groupId);
            }

            JSONArray jsonArray = new JSONArray();
            if(null != list){
                jsonArray = toJsonArray(list);
            }

            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, ClientApiConstant.Msg.SUCCESS, jsonArray);
        }
        catch(Exception e){
            logger.error(e.getMessage());
            jo = setResponseObj(ClientApiConstant.ResultCode.SERVER_EXCEPTION, e.getMessage(),
                                ClientApiConstant.Msg.EMPTY);
        }

        renderText(jo.toString());
    }

    /**
     * @Title: isOnlyManagerVisibleOpen
     * @Description:TODO
     * @return boolean
     */
    private boolean isOnlyManagerVisibleOpen(){
        String value = "";
        List<Record> list = SysCodeType.dao.getSysCodeTypeByCode("IS_ONLY_MANAGER_VISIBLE_SWITCH");
        if(list.size() > 0){
            value = list.get(0).getStr(SysCodeValue.VALUE);
            logger.info("is only manager visible switch:" + value);
            if("1".equals(value)){
                return true;
            }
        }

        return false;
    }

}
